import 'package:fishing/providers/auth_provider.dart';
import 'package:fishing/providers/community_provider.dart';
import 'package:fishing/providers/home_provider.dart';
import 'package:fishing/providers/fishing_provider.dart';
import 'package:fishing/providers/location_weather_provider.dart';
import 'package:fishing/providers/technique_provider.dart';
import 'package:fishing/providers/fishing_report_provider.dart';
import 'package:fishing/providers/version_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:logging/logging.dart';
import 'package:provider/provider.dart';
import 'router/app_router.dart';
import 'providers/user_provider.dart';
import 'services/websocket_manager.dart';
import 'package:flutter/services.dart';
import 'dart:ui';

void main() async {
  // 确保Flutter绑定初始化
  WidgetsFlutterBinding.ensureInitialized();
  
  // 添加全局错误捕获
  FlutterError.onError = (FlutterErrorDetails details) {
    print('Flutter Error: ${details.exception}');
    print('Stack trace: ${details.stack}');
  };
  
  // 捕获异步错误
  PlatformDispatcher.instance.onError = (error, stack) {
    print('Platform Error: $error');
    print('Stack trace: $stack');
    return true;
  };

  // 设置日志级别（通常在开发环境使用 ALL 或 FINEST）
  // 配置日志输出格式和目标（控制台）
  Logger.root.onRecord.listen((LogRecord rec) {
    // ignore: avoid_print
    if (rec.error != null) {
      // ignore: avoid_print
      // ignore: avoid_print
    }
  });
  // 设置系统UI为透明
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      // 状态栏设置
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark,
      statusBarBrightness: Brightness.light,
      
      // 导航栏设置 - 完全透明
      systemNavigationBarColor: Colors.transparent,
      systemNavigationBarIconBrightness: Brightness.dark,
      systemNavigationBarDividerColor: Colors.transparent,
    ),
  );
  
  // 先设置为普通模式，再设置边缘到边缘
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: [
    SystemUiOverlay.top,
    SystemUiOverlay.bottom,
  ]);
  
  // 延迟设置边缘到边缘模式
  Future.delayed(const Duration(milliseconds: 100), () {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
  });
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => UserProvider()),
        ChangeNotifierProvider(create: (_) => AuthProvider()),
        ChangeNotifierProvider(create: (_) => CommunityProvider()),
        ChangeNotifierProvider(create: (_) => HomeProvider()),
        ChangeNotifierProvider(create: (_) => FishingProvider()),
        ChangeNotifierProvider(create: (_) => LocationWeatherProvider()),
        ChangeNotifierProvider(create: (_) => TechniqueProvider()),
        ChangeNotifierProvider(create: (_) => FishingReportProvider()),
        ChangeNotifierProvider(create: (_) => VersionProvider()),
      ],
      child: const MyApp(),
    ),
  );
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  final WebSocketManager _wsManager = WebSocketManager();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _initializeApp();
  }

  // 初始化应用，检查登录状态
  Future<void> _initializeApp() async {
    try {
      final authProvider = context.read<AuthProvider>();
      final userProvider = context.read<UserProvider>();
      final versionProvider = context.read<VersionProvider>();
      
      // 等待认证初始化完成
      while (!authProvider.isInitialized) {
        await Future.delayed(const Duration(milliseconds: 100));
      }
      
      // 安全初始化WebSocket管理器
      try {
        await _wsManager.initialize(context);
      } catch (e) {
        print('WebSocket初始化失败: $e');
      }
      
      // 安全初始化版本信息
      try {
        await versionProvider.initVersionInfo();
      } catch (e) {
        print('版本信息初始化失败: $e');
      }
      
      // 如果已登录，尝试获取用户信息
      if (authProvider.isLoggedIn) {
        try {
          await userProvider.fetchUserInfo();
          // 自动登录成功后连接WebSocket
          if (userProvider.user != null) {
            await _wsManager.connectWithUser(userProvider.user!.userId.toString());
          }
        } catch (e) {
          print('获取用户信息失败: $e');
          // 如果获取用户信息失败，可能token已失效，清除登录状态
          await authProvider.logout();
          await _wsManager.disconnect();
        }
      }
      
      // 自动检查版本更新（延迟执行，避免影响启动速度）
      try {
        versionProvider.autoCheckOnAppStart();
      } catch (e) {
        print('版本检查失败: $e');
      }
    } catch (e) {
      print('应用初始化失败: $e');
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    
    // 当应用进入后台或被终止时清除位置缓存
    if (state == AppLifecycleState.paused || 
        state == AppLifecycleState.detached) {
      final locationProvider = context.read<LocationWeatherProvider>();
      locationProvider.clearLocationWeatherCache();
    }
  }

  @override
  Widget build(BuildContext context) {
    // 这里的 context 已经能找到 providers 了
    final userProvider = Provider.of<UserProvider>(context);
    final authProvider = Provider.of<AuthProvider>(context);

    final router = createRouter(userProvider, authProvider);

    // 在每次build时重新设置系统UI样式，使用更强制的方法
    WidgetsBinding.instance.addPostFrameCallback((_) {
      SystemChrome.setSystemUIOverlayStyle(
        const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarIconBrightness: Brightness.dark,
          systemNavigationBarColor: Colors.transparent, // 完全透明
          systemNavigationBarIconBrightness: Brightness.dark,
          systemNavigationBarDividerColor: Colors.transparent,
        ),
      );
    });

    return MaterialApp.router(
      debugShowCheckedModeBanner: false,
      routerConfig: router,
      title: '鱼乐无限',
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('zh', 'CN'),
        Locale('en', 'US'),
      ],
      theme: ThemeData(
        primaryColor: Colors.blue,
        primarySwatch: Colors.blue,
        colorScheme:
            ColorScheme.fromSwatch(primarySwatch: Colors.blue).copyWith(
          secondary: Colors.blueAccent,
          primary: Colors.blue,
          onPrimary: Colors.white,
          surface: Colors.white,
          onSurface: Colors.black87,
          error: Colors.red,
          onError: Colors.white,
        ),
        appBarTheme: const AppBarTheme(
          backgroundColor: Colors.blue,
          foregroundColor: Colors.white,
          elevation: 0,
          centerTitle: true,
        ),
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.blue,
            foregroundColor: Colors.white,
            disabledBackgroundColor: Colors.blue.shade100,
            disabledForegroundColor: Colors.white70,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
        ),
        textSelectionTheme: const TextSelectionThemeData(
          cursorColor: Colors.blue,
        ),
        inputDecorationTheme: const InputDecorationTheme(
          labelStyle: TextStyle(color: Colors.grey),
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.grey, width: 1.0),
          ),
          focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Color(0xFF4286DE)),
          ),
          errorBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.red, width: 1.0),
          ),
          focusedErrorBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.red, width: 2.0),
          ),
          floatingLabelBehavior: FloatingLabelBehavior.auto,
          contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        ),
      ),
    );
  }
}
